//
//  ChaosDownload.m
//  Chaos
//
//  Created by Worker on 5/18/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ChaosPhotoDownload.h"


@implementation ChaosPhotoDownload
@synthesize delegate;
@synthesize identifier;
@synthesize url;
@synthesize downloadedPhotoData;
@synthesize photoData;
@synthesize photoConnection;

- (void)dealloc
{
	[url release];
	[downloadedPhotoData release];
	url = nil;
	delegate = nil;
	[identifier release];
	identifier = nil;
	[super dealloc];
}

- (id)initWithIdentifier:(id)identifierParam withURL:(NSString *)urlParam
{
	self = [super init];
	if ( self )
	{
		identifier = [identifierParam retain];
		url = [urlParam retain];
	}
	return self;
}

- (void)startDownload
{
    self.photoData = [NSMutableData data];
	
	NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:url]
											  cachePolicy:NSURLRequestUseProtocolCachePolicy
										  timeoutInterval:60.0];
	NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
	
	self.photoConnection = conn;
	[conn release];
}

- (void)cancelDownload
{
    [self.photoConnection cancel];
    self.photoConnection = nil;
    self.photoData = nil;
}

#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	expectedSize = [response expectedContentLength];
	float kLen = (float)expectedSize / 1024.0f;
	NSLog(@"Expected Size: %.2fK, [url=%@]", kLen, self.url);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.photoData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	if (self.delegate)
	{
		[self.delegate photoDidDownload:nil];
	}
    self.photoData = nil;
    self.photoConnection = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	if (self.photoData) {
		NSUInteger len = [self.photoData length];
		float kLen = (float)len / 1024.0f;
		NSLog(@"---------Get Response Size: %.2fK, [url=%@]", kLen, self.url);
		[downloadedPhotoData release];
		downloadedPhotoData = [self.photoData retain];
		if (self.delegate)
		{
			[self.delegate photoDidDownload:self.identifier];
		}
	}
	
    self.photoData = nil;
    self.photoConnection = nil;
}

@end
